import updateTreeNodeInfo, { getFullTreeByXid, getTreeNodeInfoById } from "@/services/basis";
import { ProCard, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormText } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Card, Col, DatePicker, Flex, Form, Input, message, Radio, Row, Space, Tree, TreeDataNode } from "antd";
import { times } from "lodash";
import moment from "moment";
import { useRef, useState } from "react";

const App:React.FC=()=>{
    const [trNode,setTrNode]=useState<{key:any,title:string}>({key:0,title:''});
    const [trData,setTrData]=useState<TreeDataNode[]>([]);
    const [etype,setEtype]=useState(0);
    const [expandKeys,setExpandKeys]=useState([]);

    const form_ref=useRef<ProFormInstance>();

    useRequest(()=>getFullTreeByXid({x_id:1,treeType:'base_organization'}),{
        onSuccess:(data)=>{
          setTrData(data.ctree);
          setExpandKeys(data.keys);
        },
    });

    async function getTreeNodeInfo(node:{key:any,title:any}){
          // alert(JSON.stringify(node));
         setEtype(0);
         setTrNode(node);//保存当前的id，在新增时使用
        const info=await getTreeNodeInfoById({treeType:'v_organization',key:node.key});
        const fdata={...info.data,
                     operate_time:moment(moment(info.data.operate_time).toDate()).format('YYYY-MM-DD')
              };

       form_ref.current?.setFieldsValue({
                 code:fdata.code,name:fdata.name,higher_name:fdata.higher_name,
                 operate_time:fdata.operate_time,higher_code:fdata.higher_code,
                 status:fdata.status,operater_id:fdata.operater_id,
                 type:fdata.type,x_id:fdata.x_id,
                 }); 
      }
 
      //新增
      async function add(){
         if(trNode.key==0)
             message.warning('请先选择所归属的类别！');
         else{
          setEtype(1);
          form_ref.current?.resetFields();
          form_ref.current?.setFieldsValue({
             operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),
             higher_code:trNode.title.substring(0,trNode.title.indexOf(' ')),
             higher_name:trNode.title.substring(trNode.title.indexOf(' '+1)),
             type:2,
         });
         };
      };
 
      //保存
      async function save(){
         const fdata=form_ref.current?.getFieldsValue();
         const fdata2={...fdata,higher_id:trNode?.key, 
                        higher_code:trNode?.title.substring(0,trNode?.title.indexOf(' ')), 
                        id:trNode?.key, 
                       operate_time:moment(moment(fdata.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
        //  alert(JSON.stringify(fdata2));
        //mform_ref.current?.submit();
        // alert(etype);
        const r=await updateTreeNodeInfo({x_id:1,operater_id:1,ttype:etype,tdata:fdata2,treeType:'base_organization'});
         if(r.success){
           message.success('数据保存成功！');
           //alert(JSON.stringify(r.data));
           setTrData(r.data);
           }
         else
           message.error('数据保存失败， 请检查。');
     
      }
    
    return(
     <Row gutter={8} >
         <Col span={6}>
         <ProCard title='组织架构' style={{height:700}}>
            {/* <Tree treeData={trData} defaultExpandAll={true}
              onClick={(e,node)=>getTreeNodeInfo({key:node.key,title:node.title?.toString()})}
            /> */}
            <Tree treeData={trData}   blockNode={true}  expandedKeys={expandKeys}
               onClick={(e,node)=>getTreeNodeInfo({key:node.key,title:node.title?.toString()})}
               onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
            />
         </ProCard>
         </Col>
         <Col span={18}>
         <ProCard title='组织基本信息' style={{height:700}} 
              extra={<Space>
                <Button onClick={()=>add()}>新增</Button>
                <Button onClick={()=>form_ref.current?.submit()}>保存</Button>
              </Space>}>
            <ProForm labelCol={{span:8}}   submitter={false} formRef={form_ref}
                style={{width:500,marginLeft:100}}  labelWrap={false}
                initialValues={{status:1,operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),operater_id:1}}
                onFinish={()=>save()}
            >
                <ProFormText name='code' label='部门编码' rules={[{required:true,message:'必输项'}]}/>
                <ProFormText name='name' label='部门名称' rules={[{required:true,message:'必输项'}]}/>
                <ProFormText name='higher_code' label='上级编码' disabled/>
                <ProFormText name='higher_name' label='上级名称' disabled/>
                <ProFormRadio.Group name='status' label='状态'
                       options={[{label:'正常',value:1},{label:'冻结',value:2},{label:'删除',value:3}]}/>
                <ProFormRadio.Group name='type' label='类别' 
                    options={[{label:'业务单元',value:1},{label:'部门',value:2}]} />
                <Row gutter={8}>
                  <Col span={12}> 
                      <ProFormDatePicker name='operater_time' label='修改时间'   />
                   </Col>
                   <Col span={12}>
                      <ProFormText name='operater_id' label='修改人' />
                   </Col>
                </Row>    
            </ProForm>
         </ProCard>
         </Col>
     </Row>
);
}

export default App;